﻿/* Copyright (c) 2008 Google Inc.
*  Copyright (c) 2009 Pierre Henri Kuate.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using org.opensocial.client;

namespace OpenSocial.Sample.Web
{
	public partial class Default : System.Web.UI.Page
    {
        private static readonly System.Text.StringBuilder _log = new System.Text.StringBuilder();

        public void Log(object obj)
        {
            _log.AppendLine(System.DateTime.Now.ToLongTimeString() + ": " + obj);
            LogText.Text = "Log:\n" + _log;
        }


		protected void Page_Load(object sender, System.EventArgs e)
        {
            try
            {
                var KnownGadgets = new System.Collections.Generic.Dictionary<string, Gadget>();
                KnownGadgets.Add("926348996252", new Gadget // http://opensocial-net-client.googlecode.com/svn/trunk/src/OpenSocial.Sample.Web/gadget.xml
                {
                    ConsumerSecret = "iqzEMa0ptEiceSqocSvM4CH6",
                    OutgoingConsumerKey = "orkut.com:926348996252",
                    Container = OpenSocialProvider.ORKUT_SANDBOX
                });
                KnownGadgets.Add("623061448914", new Gadget // http://opensocial-resources.googlecode.com/svn/samples/rest_rpc/sample.xml
                {
                    ConsumerSecret = "uynAeXiWTisflWX99KU1D2q5",
                    OutgoingConsumerKey = "orkut.com:623061448914",
                    Container = OpenSocialProvider.ORKUT_SANDBOX
                });
                KnownGadgets.Add("http://opensocial-net-client.googlecode.com/svn/trunk/src/OpenSocial.Sample.Web/gadget.xml", new Gadget
                {
                    ConsumerSecret = "39a9cf3a98344e928f98d2fa6064d759",
                    OutgoingConsumerKey = "http://opensocial-net-client.googlecode.com/svn/trunk/src/OpenSocial.Sample.Web/gadget.xml",
                    Container = OpenSocialProvider.MYSPACE
                });
                KnownGadgets.Add("http://opensocial-resources.googlecode.com/svn/samples/rest_rpc/sample.xml", new Gadget
                {
                    ConsumerSecret = "6a838d107daf4d09b7d446422f5e7a81",
                    OutgoingConsumerKey = "http://opensocial-resources.googlecode.com/svn/samples/rest_rpc/sample.xml",
                    Container = OpenSocialProvider.MYSPACE
                });
                KnownGadgets.Add("hi5.com", new Gadget // TODO: Doesn't need signing
                {
                    ConsumerSecret = "",
                    OutgoingConsumerKey = "",
                    Container = OpenSocialProvider.HI5_SANDBOX
                });


                Log("Default.aspx: SessionId=" + Session.SessionID);
                Log("Url: " + Request.Url);
                Log("IsPostBack: " + IsPostBack);
                Log("POST Form: " + Request.Form);
                //Log("ServerVariables: " + Request.ServerVariables);
                Session["ForceKeepingTheSessionState"] = "Random value"; // TODO: For debugging only; if everything works, the OpenSocialClient will be in the session state, forcing it to be kept


                if (!SessionManager.ExtractSession(Request)) // If not authenticated yet
                {
                    ShowFriends.Enabled = ShowAlbumsAndPhotos.Enabled = false;
                    OpenSocialClient client;
                    if (SessionManager.CreateSession(Request, KnownGadgets, out client)) // If signed request found and valid
                    {
                        Output.Text = "Session created; loading IFrame...";
                        SessionManager.WriteIFrame(Request.Url.AbsoluteUri, Response, client);
                    }
                    else
                    {
                        Output.Text = "Invalid request; Show error message or redirect to the login page!";
if (string.IsNullOrEmpty(Request.QueryString["opensocial_session_id"])) { // TODO: Remove when OpenSocialRequestValidator.verifyHmacSignature() works
    if (client == null) client = new OpenSocialClient(KnownGadgets["623061448914"]);
    ShowFriends.Enabled = ShowAlbumsAndPhotos.Enabled = true;
    SessionManager.AddClient(client);
    SessionManager.WriteIFrame(Request.Url.AbsoluteUri, Response, client);
}
                    }
                }
                else
                {
                    var client = SessionManager.Client;
                    if (string.IsNullOrEmpty(client.OwnerId) && string.IsNullOrEmpty(client.ViewerId))
                        Output.Text = "Render Preview";
                    else if (client.OwnerId == client.ViewerId)
                        Output.Text = "Render Owner";
                    else if (!string.IsNullOrEmpty(client.ViewerId))
                        Output.Text = "Render ViewerWithAppInstalled"; // TODO: Is it possible for OwnerId to be null? If so, what does it mean?
                    else
                        Output.Text = "Render ViewerWithoutAppInstalled";
                    Output.Text += ": { OwnerId=" + client.OwnerId
                        + "; ViewerId=" + client.ViewerId
                        + "; view=" + client.View + "; }";
                }
            }
            catch (System.Threading.ThreadAbortException)
            {
                Output.Text += "\nPage rendering aborted";
            }
            catch (System.Exception ex)
            {
                Output.Text = ex.GetType() + ": " + ex.Message;
                Log(ex);
            }
            finally
            {
                Log("IsAuthenticated: " + SessionManager.IsAuthenticated);
                Log("Output.Text: " + Output.Text);
                Log("END of Page_Load()\n\n\n");
            }
        }



        protected override void OnPreRender(System.EventArgs e)
		{
            // Needed because we are using IFrame and ASP.NET stores its SessionId in a cookie. Ref: http://www.w3.org/P3P/ and http://msdn2.microsoft.com/en-us/library/ms537343.aspx
            // If Internet Explorer is set on medium privacy level, it will block third-party cookies that do not have a compact privacy policy
			Response.AppendHeader("P3P", "CP=\"CAO PSA OUR\"");
            base.OnPreRender(e);
        }



        protected void TestPost_Click(object sender, System.EventArgs e)
        {
            Output.Text = "Test: IsAuthenticated=" + SessionManager.IsAuthenticated;
            Log(Output.Text + "\n");
		}

        protected void ShowFriends_Click(object sender, System.EventArgs e)
        {
            if (!SessionManager.IsAuthenticated)
            {
                Log("ShowFriends: Session expired.\n");
                return;
            }
            Output.Text = "Friends";
            var c = SessionManager.Client;
            Log(c.fetchPerson());
            Log(c.fetchFriends());
            Log("END\n\n\n");
        }

        protected void ShowAlbumsAndPhotos_Click(object sender, System.EventArgs e)
        {
            if (!SessionManager.IsAuthenticated)
            {
                Log("ShowAlbumsAndPhotos: Session expired.\n");
                return;
            }
            Output.Text = "AlbumsAndPhotos";
            var c = SessionManager.Client;
            var friends = c.fetchFriends();
            friends.Insert(0, c.fetchPerson());

            foreach (var friend in friends)
            {
                Log(friend);
                try
                {
                    var albums = c.fetchAlbums(friend.Id); // TODO: Orkut returns "unauthorized: You can only access @viewer's albums."
                    foreach (var album in albums)
                    {
                        Log(album);
                        Log(c.fetchMediaItems(album.OwnerId, "@self", album.Id) + "\n");
                    }
                }
                catch (System.Exception ex)
                {
                    Log("Albums not accessible:\n" + ex.Message);
                }
                Log("----------------------------------------\n\n");
            }
            Log("END\n\n\n");
        }
	}
}
